package c926.xiaoduyun.xiaodu.plugin.other;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import kd.bos.openapi.common.constant.ApiErrorCode;
import kd.bos.openapi.common.constant.MediaType;
import kd.bos.openapi.common.exception.OpenApiException;
import kd.bos.openapi.common.spi.ICustomApiServlet;
import kd.bos.openapi.common.util.IOUtil;
import kd.bos.openapi.common.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

public class CustomDemoServletApi implements ICustomApiServlet {

    private static final Log log = LogFactory.getLog(CustomDemoServletApi.class);
    private String inputPara, outputPara;

    private void setInputPara(String data) {
        this.inputPara = data;
    }

    private void setOutputPara(String data) {
        this.outputPara = data;
    }

    /**
     * 获取入参参数，用于API日志
     */
    @Override
    public String getInputParameter() {
        return inputPara;
    }

    /**
     * 获取出参参数，用于API日志
     */
    @Override
    public String getOutputParameter() {
        return outputPara;
    }

    /**
     * 操作HttpServlet对象
     * 1. 自行开发的Servlet-API接口仍然受认证鉴权、API安全、IP策略、限流策略等统一控制；
     * 2. 只允许处理当前数据中心的上下文（当前数据中心的RequestContext），不能创建新的线程；
     */
    @Override
    public void doAction(HttpServletRequest req, HttpServletResponse resp) {
        String inputData = "", result = "";
        try {
            //1、处理入参（获取HttpServletRequest）
            req.setCharacterEncoding("utf-8");
            String userName = req.getParameter("username") == null ? "" :
                    req.getParameter("username");
            inputData = "用户名：" + userName;
            this.setInputPara(inputData); //将入参记录下来，用于API日志
            //2、执行业务处理
            result = "自定义ServletAPI处理逻辑，对数据进行处理示例。您的输入示例数据是：" + inputData + "，当前日期：" + (new Date()).toString();
            //示例：你可以调用微服务，业务代码请放在二开业务JAR包中，并部署在相应业务节点容器上
            //result =DispatchServiceHelper.invokeBizService("testCloudId",
            // "testAppId", "TestService", "testMethod", inputData);
            //3、输出结果(操作HttpServletResponse）
            this.setOutputPara(result); //将出参记录下来，用于API日志
            writeData(result, resp); //"application/json"
        } catch (Exception ex) {
            //记录日志
            log.error(String.valueOf(ex));
            throw new OpenApiException(ex, ApiErrorCode.HTTP_BAD_REQUEST,
                    ex.getMessage());
        }
    }

    //写HttpServletResponse流
    private void writeData(String data, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            if (StringUtil.isEmpty(data)) {
                response.setContentLength(0);
            } else {
                outputStream = response.getOutputStream();
                response.setContentType(MediaType.TEXT_PLAIN);
                outputStream.write(data.getBytes());
                outputStream.flush();
            }
        } catch (IOException ex) {
            throw new OpenApiException(ex, ApiErrorCode.HTTP_INTERNAL_ERROR,
                    ex.getMessage());
        } finally {
            //记得关闭流
            IOUtil.closeQuietly(outputStream);
        }
    }

}
